package com.example.taskdemo;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.util.Log;


import com.example.taskdemo.services.AIUIService;

import java.util.List;


public class MApplication extends Application {
    private static final String TAG = "MApplication";
    private static Context mApplication;

    public static Context getInstance(){
        return mApplication;
    }



    @Override
    public void onCreate() {
        super.onCreate();
        mApplication = getApplicationContext();
        startAIUIService();
    }


    public static void startAIUIService(){
        if(!isServiceRunning(AIUIService.class.getName())) {
            Log.d(TAG, "startAIUIService: ");
            mApplication.startService(new Intent(mApplication, AIUIService.class));
        }
    }


    /**
     * 检测后台是否开启
     * @param className
     * @return
     */
    public static Boolean isServiceRunning(String className){
        ActivityManager activityManager = (ActivityManager) mApplication.getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> list = activityManager.getRunningServices(Integer.MAX_VALUE);
        for (int i = 0; i < list.size(); i++) {
            if(list.get(i).service.getClassName().equals(className)){
                Log.d(TAG, "isServiceRunning: 服务已开启"+className);
                return true;
            }
        }
        Log.d(TAG, "isServiceRunning: 服务未开启");
        return false;
    }
}
